import {
  CloudUploadOutlined,
  DeleteOutlined,
  EyeOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import { Button, Col, message, Row, Tooltip, Upload } from "antd";
import React, { useState } from "react";
import PopconfirmButton from "@/components/PopconfirmButton";
import { uploadFile } from "@/services/file";
import { isPDF } from "@/utils";
import { gutter } from "../const/keys";
import { ColorText, getTextByStatus } from "../product/ImportModal";

let timer: NodeJS.Timeout;
type Props = {
  onEevent?: (type: "start" | "end", data?: any) => void;
  defaultFileList?: any[];
  onUploadComplete: (files: any[]) => void;
};
//支持预览的格式，PDF，图片
let fileLength = 0;
let changeIndex = 0;
const App: React.FC<Props> = ({
  onEevent = () => {},
  onUploadComplete,
  defaultFileList,
}) => {
  const [fileList, setFileList] = useState<any[]>(defaultFileList || []);
  const [uploading, setUploading] = useState(false);
  const uploadFileStart = async () => {
    try {
      setUploading(true);
      onEevent("start");
      for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i];
        if (file.status === "done" || file.status === "error") {
          continue; //跳过已上传或上传失败的文件
        }
        //模拟上传过程
        file.status = "uploading";
        setFileList([...fileList]);
        const formData = new FormData();
        formData.append("name", "file");
        formData.append("file", file);

        const { success, msg, data } = await uploadFile(formData);

        if (success) {
          file.status = "done";
          file.createTime = data.createTime;
          file.fileName = data.fileName;
          file.originalName = data.name;
          file.filePath = data.filePath;
          file.fileSize = data.fileSize;
          file.fileType = data.fileType;
          file.id = data.id;
          file.uid = data.id;
        } else {
          file.status = "error";
          file.msg = msg;
          message.error(`文件 ${file.name} 上传失败: ${msg}`);
        }
        setFileList([...fileList]);

        //保留done的文件
        onUploadComplete(fileList.filter((f) => f.status === "done"));
      }
      setUploading(false);
      onEevent("end");
    } catch (error) {
      console.error(error);
      setUploading(false);
      onEevent("end");
    }
  };
  const uploadProps: UploadProps = {
    multiple: true,
    accept: ".rar,.zip,.doc,.pdf",
    showUploadList: false,
    beforeUpload: (file, files) => {
      fileLength = files?.length;
      console.log("beforeUpload", files?.length, file, fileList);
      //不能超过20MB
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        message.error(`文件：" ${file.name} " 超过 20MB，已跳过`);
        return;
      }
      //如果不是支持的类型

      setFileList((prevList) => [...prevList, file]);
      return false; // 阻止自动
    },
    onChange(_info) {
      changeIndex++;
      console.log(fileLength, changeIndex);
      if (changeIndex < fileLength) {
        return;
      }
      onEevent("start");

      clearTimeout(timer);
      timer = setTimeout(() => {
        uploadFileStart();
      }, 500);
    },
  };
  //本地预览PDF
  const handlePreview = (file: any) => {
    const disabled = !isPDF(file.fileType);
    //看是否包含支持的格式
    if (disabled) {
      message.warning("不支持预览该文件格式！");
      return;
    }
    console.log(file);

    try {
      const fileURL = URL.createObjectURL(file);
      window.open(fileURL);
    } catch (error) {
      console.error("Error opening file:", error);
      //如果是http地址则直接打开
      if (file?.filePath?.startsWith("http")) {
        window.open(file.filePath);
        return;
      }
      console.error("Error opening file:", error);
    }
  };
  return (
    <Row gutter={[gutter, gutter]}>
      <Col span={24}>
        <Row gutter={[gutter, gutter]} align={"bottom"}>
          <Col>
            <Upload {...uploadProps}>
              <Button disabled={uploading} icon={<CloudUploadOutlined />}>
                上传附件
              </Button>
            </Upload>
          </Col>
          <Col style={{ color: "gray" }}>
            支持格式：.rar .zip .doc .pdf，单个文件不能超过20MB
          </Col>
        </Row>
      </Col>
      <Col
        span={24}
        style={{
          minHeight: 300,
          maxHeight: 300,
          overflowY: "auto",
        }}
      >
        <Row gutter={[gutter, 0]}>
          {fileList?.map((file, index) => (
            <Col key={`${index}${file.id}`} span={24}>
              <Row gutter={[gutter, 10]} wrap={false}>
                <Col flex={"auto"}>
                  <div
                    className="div"
                    style={{
                      maxWidth: "90%",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}
                  >
                    {index + 1}、{" "}
                    <Tooltip
                      title={file.originalName || file.name || file.fileName}
                    >
                      {file.originalName || file.name || file.fileName}
                    </Tooltip>
                  </div>
                </Col>
                <Col flex={"250px"}>
                  <Row justify={"end"}>
                    <Col>
                      <ColorText type={file.status as any}>
                        {file.isOldFile ? null : getTextByStatus(file.status)}
                      </ColorText>
                    </Col>
                    <Col>
                      <Button
                        disabled={!isPDF(file.fileType) || uploading}
                        icon={<EyeOutlined />}
                        type="link"
                        size="small"
                        onClick={() => handlePreview(file)}
                      >
                        预览
                      </Button>
                    </Col>
                    <Col>
                      <PopconfirmButton
                        disabled={uploading}
                        onConfirm={() => {
                          const newList = fileList.filter(
                            (_item, i) => i !== index
                          );
                          setFileList(newList);
                          onUploadComplete(newList);
                        }}
                        title={`确定要删除 ${
                          file.originalName || file.name || file.fileName
                        } 吗？`}
                        icon={<DeleteOutlined />}
                        type="link"
                        size="small"
                      >
                        删除
                      </PopconfirmButton>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </Col>
          ))}
        </Row>
      </Col>
    </Row>
  );
};

export default App;
